<template>
  <div class="simple-tag-selector">
    <el-select
      v-model="selectedTagIds"
      multiple
      filterable
      remote
      reserve-keyword
      placeholder="请选择文章标签"
      :remote-method="searchTags"
      :loading="loading"
      style="width: 100%"
      @change="handleChange"
    >
      <el-option v-for="tag in availableTags" :key="tag.id" :label="tag.name" :value="tag.id">
        <div style="display: flex; gap: 8px; align-items: center">
          <div
            :style="{
              width: '12px',
              height: '12px',
              borderRadius: '50%',
              backgroundColor: tag.color || '#409eff'
            }"
          />
          <span>{{ tag.name }}</span>
          <span style=" font-size: 12px;color: #8492a6">(权重: {{ tag.weight }})</span>
        </div>
      </el-option>
    </el-select>

    <!-- 已选标签显示 -->
    <div v-if="false" class="selected-tags-display" style="margin-top: 8px">
      <el-tag
        v-for="tag in selectedTags"
        :key="tag.id"
        :color="tag.color"
        :style="{
          backgroundColor: tag.color,
          color: getTextColor(tag.color),
          borderColor: tag.color,
          marginRight: '4px',
          marginBottom: '4px'
        }"
        closable
        size="small"
        @close="removeTag(tag.id)"
      >
        {{ tag.name }}
      </el-tag>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import type { TagInfo } from "@/api/tag-management";

// Props
const props = defineProps<{
  modelValue: TagInfo[];
  maxTags?: number;
}>();

// Emits
const emit = defineEmits<{
  "update:modelValue": [tags: TagInfo[]];
  change: [tags: TagInfo[]];
}>();

// 响应式数据
const loading = ref(false);
const availableTags = ref<TagInfo[]>([]);
const selectedTagIds = ref<number[]>([]);

// 计算属性
const selectedTags = computed(() => {
  // 确保返回的是数组
  return Array.isArray(props.modelValue) ? props.modelValue : [];
});

// 监听 modelValue 变化
watch(
  () => props.modelValue,
  newTags => {
    // 确保 newTags 是数组
    if (Array.isArray(newTags)) {
      selectedTagIds.value = newTags.map(tag => tag.id) || [];
    } else {
      selectedTagIds.value = [];
    }
  },
  { immediate: true }
);

// 搜索标签（使用真实API）
const searchTags = async (query: string) => {
  loading.value = true;

  try {
    const params = {
      name: query || undefined,
      status: 1, // 只获取启用的标签
      per_page: 20
    };

    // 动态导入 getTags API
    const { getTags } = await import("@/api/tag-management");
    const response = await getTags(params);

    if (response.code === 200) {
      // 修复数据结构访问问题
      availableTags.value = response.data.list || [];
    } else {
      ElMessage.error("获取标签列表失败");
      availableTags.value = [];
    }
  } catch (error) {
    console.error("获取标签失败:", error);
    ElMessage.error("获取标签列表失败");
    availableTags.value = [];
  } finally {
    loading.value = false;
  }
};

// 处理选择变化
const handleChange = (tagIds: number[]) => {
  if (props.maxTags && tagIds.length > props.maxTags) {
    ElMessage.warning(`最多只能选择 ${props.maxTags} 个标签`);
    selectedTagIds.value = tagIds.slice(0, props.maxTags);
    return;
  }

  const newTags = tagIds.map(id => {
    const existingTag = selectedTags.value.find(tag => tag.id === id);
    if (existingTag) return existingTag;

    const availableTag = availableTags.value.find(tag => tag.id === id);
    return (
      availableTag || {
        id,
        name: `标签${id}`,
        color: "#409eff",
        weight: 1,
        type: 2
      }
    );
  });

  emit("update:modelValue", newTags);
  emit("change", newTags);
};

// 移除标签
const removeTag = (tagId: number) => {
  const newTags = selectedTags.value.filter(tag => tag.id !== tagId);
  selectedTagIds.value = newTags.map(tag => tag.id);
  emit("update:modelValue", newTags);
  emit("change", newTags);
};

// 工具函数：根据背景色计算文字颜色
const getTextColor = (backgroundColor?: string) => {
  if (!backgroundColor) return "#000000";
  const hex = backgroundColor.replace("#", "");
  const r = parseInt(hex.substr(0, 2), 16);
  const g = parseInt(hex.substr(2, 2), 16);
  const b = parseInt(hex.substr(4, 2), 16);
  const brightness = (r * 299 + g * 587 + b * 114) / 1000;
  return brightness > 128 ? "#000000" : "#ffffff";
};

// 初始化
searchTags("");
</script>

<style scoped>
.simple-tag-selector {
  width: 100%;
}

.selected-tags-display {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}
</style>
